'use strict';

angular.module('backofficeApp.questionManager.controllers', []).
    controller('questionListCtrl', ['$scope', 'questionManager', '$location', function ($scope, questionManager, $location) {
        //获取所有问题列表
        $scope.questionList = questionManager.getQuestionList();

        //跳转到问题增加页面
        $scope.gotoQuestionAddPage = function () {
            $location.path('/questionManager/add');
        };

        //跳转到问题修改页面
        $scope.gotoQuestionEditPage = function (objId) {
            $location.path('/questionManager/edit/' + objId);
        };

        //搜索问题表
        $scope.searchQuestion = function (question) {
            $scope.questionList = questionManager.searchQuestion(question);
        };

        //删除一个提问
        $scope.deleteQuestion = function (objId) {
            $scope.msg = questionManager.deleteQuestion(objId);
            $scope.questionList = questionManager.getQuestionList();
        };

        //修改顺序
        $scope.changeQuestionOrder = function (question) {
            $scope.msg = questionManager.changeQuestionOrder(question);
            $scope.questionList = questionManager.getQuestionList();//仅仅调用一次不能刷新？需要调用两次
            $scope.questionList = questionManager.getQuestionList();
        };

        //进入回答详情页
        $scope.gotoReplyPage = function (objId, token) {
            $location.path('/questionManager/reply/' + objId + '/' + token);
        };
    }

    ]).controller('questionEditCtrl', ['$scope', '$routeParams', 'questionManager', 'MasterDataService', '$location', function ($scope, $routeParams, questionManager, masterDataService, $location) {

        var community = $routeParams.community;
        var category = $routeParams.category;
        var tag = $routeParams.tagflg;
        var replie = $routeParams.replieflg;
        var desc = $routeParams.description;
        var nick = $routeParams.nickname;
        var startdate = $routeParams.startDate;
        var enddate = $routeParams.endDate;
        var level = $routeParams.level;

        console.debug(startdate + '---' + enddate);
        //:tagflg/:replieflg/:nickname/:description
        //var commId = $routeParams.communityId == 'al
        //var cate = $routeParams.category == 'all' ?
        //var istag = $routeParams.tagflg == 'all' ? n
        //var isreplie =  $routeParams.replieflg == 'a
        //var desc = $routeParams.description == 'empt
        //var nick = $routeParams.nickname == 'empty'

        $scope.question = questionManager.getQuestionById({objId: $routeParams.objId});
        $scope.tag = masterDataService.getAllDicService({category: '02'});

        $scope.data = new Array();
        $scope.toggle = function (ck, objId) {
            !ck ? $scope.data.push(objId) : $scope.data.remove(objId);
        };

        //var s = questionManager.getQuestionById({objId: $routeParams.objId});
        ////$scope.imgs = $scope.question.data.images;
        //console.debug('ssssss');
        //console.debug(s);
        //var slides = $scope.slides = [];
        //for()
        //slides.push({ image: url);

        //Zoom
        //$scope.zoomImg = function(){
        //    if($(this).style("width")==100)
        //    {
        //        $(this).css({width:'360px'});
        //    }else{
        //        $(this).css({width:'100px'});
        //    }
        //}

        //更新问题
        $scope.updateQuestion = function () {
            var temp = {
                "desc": $scope.question.data.desc,
                "tag": $scope.data
            };

            questionManager.updateQuestion({objId: $routeParams.objId}, temp);
            $location.path('/recommendQuestion/' + community + '/' + category + '/' + tag + '/' + replie + '/' + nick + '/' + desc + '/' + startdate + '/' + enddate + '/' + level);
        };

        //返回到问题列表页面
        $scope.gotoQuestionListPage = function () {
            $location.path('/recommendQuestion/' + community + '/' + category + '/' + tag + '/' + replie + '/' + nick + '/' + desc + '/' + startdate + '/' + enddate + '/' + level);
        };


    }]).controller('replyListCtrl', ['$scope', '$routeParams', 'questionManager', '$location', function ($scope, $routeParams, questionManager, $location) {
        //获取所有回复列表
        $scope.replyList = questionManager.getReplyList({objId: $routeParams.objId, token: $routeParams.token});
        var questionId = $routeParams.objId;

        //搜索问题表
        $scope.searchReply = function (reply) {
            $scope.replyList = questionManager.searchReply({questionId: questionId, key: reply.key});
        };

        //删除一个回复
        $scope.deleteReply = function (objId) {
            $scope.msg = questionManager.deleteReply({
                questionId: questionId,
                replyId: objId,
                token: $routeParams.token
            });
            $scope.replyList = questionManager.getReplyList({objId: $routeParams.objId, token: $routeParams.token});
        };

    }]).controller('noReplyCtrl', ['$scope', 'questionManager', '$routeParams', 'CommunityService', '$http', function ($scope, questionManager, $routeParams, communityService, $http) {

        $scope.communityLabelList = communityService.getAllCommunityService();
        //获取所有未回复问题列表

        function refresh() {
            $scope.communityLabelList = communityService.getAllCommunityService();
        }


        //setInterval(function () {
        //    $scope.noReplyList = questionManager.getNoReplyQuestion({token:0},{objId: '1'});
        //}, 5000);

        $scope.noReplyList = questionManager.getNoReplyQuestion({token: 0}, {objId: '1'});
        $scope.getNoReplyList = function (date, communityId) {
            if (date == null) {
                date = 0
            }
            if (communityId == null) {
                communityId = '1'
            }

            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/question/getFreshNewsQuestion', {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.freshQuestion = data.data;

                result.forEach(function (question) {
                    $scope.freshQuestion.forEach(function (fresh) {
                        if (question.objId == fresh.newsId) {
                            question['isFresh'] = true
                        }
                    });
                });
                $scope.recommendList = result;
            }).error(function () {
            });


            $scope.noReplyList = questionManager.getNoReplyQuestion({token: date}, {objId: communityId});
        };

        $scope.sendReply = function (questionId, reply) {

            if (reply == null) {
                alert('回复内容不能为空')
            } else {
                var v = questionManager.postReply({objId: questionId}, reply);

            }
        }
    }
    ]).controller('reportCtrl', ['$scope', 'questionManager', '$routeParams', 'CommunityService', '$location', '$http', function ($scope, questionManager, $routeParams, communityService, $location, $http) {

        $scope.communityLabelList = communityService.getAllCommunityService();

        var commId = '1';

        $scope.getQuestionList = function (communityId) {
            if (communityId == null) {
                communityId = '1'
            }

            commId = communityId;
            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/question/getReportQuestion/' + communityId, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.questionList = data.data;
            }).error(function () {
                $scope.questionList = null;
            });
        };

        $scope.getQuestionList(commId);

        //删除问题
        $scope.deleteReportQuestion = function (questionId) {
            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/question/deleteReportQuestion/' + questionId, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.getQuestionList(commId);
            }).error(function () {

            });
        }

    }
    ]).controller('recommendCtrl', ['$scope', 'questionManager', '$routeParams', 'CommunityService', '$location', '$http', function ($scope, questionManager, $routeParams, communityService, $location, $http) {


        var commId = $routeParams.communityId == 'all' ? null : $routeParams.communityId;
        var cate = $routeParams.category == 'all' ? null : $routeParams.category;
        var istag = $routeParams.tagflg == 'all' ? null : $routeParams.tagflg;
        var isreplie = $routeParams.replieflg == 'all' ? null : $routeParams.replieflg;
        var desc = $routeParams.description == 'empty' || $routeParams.description == '' ? null : $routeParams.description;
        var nick = $routeParams.nickname == 'empty' || $routeParams.nickname == '' ? null : $routeParams.nickname;

        var startdate = $routeParams.startDate == 'empty' || $routeParams.startDate == '' ? null : $routeParams.startDate;
        var enddate = $routeParams.endDate == 'empty' || $routeParams.endDate == '' ? null : $routeParams.endDate;
        var level = $routeParams.level == 'all' ? null : $routeParams.level;


        $scope.communityId = commId;
        $scope.category = cate;
        $scope.tagflg = istag;
        $scope.replieflg = isreplie;
        $scope.nickname = nick;
        $scope.description = desc;
        //$scope.cstartDate = null;
        //$scope.cendDate = null;
        $scope.level = level

        if (startdate != 'empty' && startdate != '' && startdate != 'empty' && startdate != null) {
            $('#startDate').datepicker('setDate', new Date(startdate.replace(/-/g, "/")));
        }
        if (enddate != 'empty' && enddate != '' && enddate != 'empty' && enddate != null) {
            $('#endDate').datepicker('setDate', new Date(enddate.replace(/-/g, "/")));
        }


        $scope.categoryList = [
            {
                name: '邻里求助',
                value: 'question'
            },
            {
                name: '推荐分享',
                value: 'share'
            },
            {
                name: '邻里活动',
                value: 'activity'
            },
            {
                name: '二手闲置',
                value: 'secondhand'
            },
            {
                name: '免费赠送',
                value: 'free'
            },
            {
                name: '失物招领',
                value: 'lostAndFound'
            },
            {
                name: '邻里广告',
                value: 'advertisement'
            }
        ];

        $scope.communityLabelList = communityService.getAllCommunityService();

        //获取所有问题列表


        $scope.currentPage = 1;
        $scope.totalPage = 10;
        $scope.pageSize = 30;
        $scope.pages = [];

        $scope.getRecommendList = function (communityId, category, tagflg, replieflg, nickname, description, startDate, endDate, levelFlag) {
            $scope.showErrorForQueryCondition = false;
            var opt = {};
            opt['isValid'] = true;
            //小区
            if (communityId != null) {
                opt['community'] = communityId;
                commId = communityId
            } else {
                commId = null;
            }
            //类别
            if (category != null) {
                opt['category'] = category;
                cate = category;
            } else {
                cate = null;
            }
            //标签
            if (tagflg != null) {
                opt['tagflg'] = tagflg;
                istag = tagflg;
            } else {
                tagflg = null;
            }
            //零回复
            if (replieflg != null) {
                opt['repliesflg'] = replieflg;
                isreplie = replieflg;
            } else {
                replieflg = null
            }
            //精华帖
            if (levelFlag == 'yes') {
                opt['level'] = 1;
                level = levelFlag;
            } else if (levelFlag == 'no') {
                opt['level'] = 0;
                level = levelFlag;
            } else {
                level = null
            }

            //昵称
            if (nickname != null && nickname != 'empty') {
                opt['nick'] = nickname;
                nick = nickname;
            } else {
                nick = null;
            }

            //描述
            if (description != null && description != 'empty') {
                opt['desc'] = description;//模糊查询参数;
                desc = description;
            }

            //发布起止日期
            //startdate = $("#startDate").val();
            //enddate = $("#endDate").val();
            startdate = startDate;
            enddate = endDate

            //console.debug(startdate+'-------'+startdate);

            if (startdate != "" && enddate != "") {
                if (startdate > enddate) {
                    $scope.showErrorForQueryCondition = true;
                    $('#errorMsg').html('起始日期不能大于终止日期!');
                    return;
                }
            }

            if (startdate != null && startdate != "") {
                opt['startdate'] = startdate;
            }
            ;

            if (enddate != null && enddate != "") {
                opt['enddate'] = enddate;
            }
            ;

            //console.debug('opt---');
            //console.debug(opt);

            if ($scope.currentPage == 0) {
                $scope.currentPage = 1;
            }

            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/question/getRecommendQuestion/' + $scope.currentPage + '/' + $scope.pageSize, opt, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                var result = data.data.questionList;
                console.debug(result.length);
                console.debug(data.data.totalPage);
                $scope.totalPage = data.data.totalPage;
                $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/question/getFreshNewsQuestion', {
                    headers: {'Content-Type': 'application/json;charset=utf-8'}
                }).success(function (data) {
                    $scope.freshQuestion = data.data;

                    result.forEach(function (question) {
                        $scope.freshQuestion.forEach(function (fresh) {
                            if (question.objId == fresh.newsId) {
                                question['isFresh'] = true
                            }
                        });
                    });
                    $scope.recommendList = result;
                }).error(function () {
                });
            }).error(function () {
                $scope.recommendList = null;
            });
        };
        $scope.getRecommendList(commId, cate, istag, isreplie, nick, desc, startdate, enddate, level);

        $scope.selectCondition = function (communityId, category, tagflg, replieflg, nickname, description, level) {
            $scope.currentPage = 1;
            //$scope.getRecommendList(communityId, category, tag);
            communityId = communityId == null ? 'all' : communityId;
            category = category == null ? 'all' : category;
            replieflg = replieflg == null ? 'all' : replieflg;
            tagflg = tagflg == null ? 'all' : tagflg;
            nickname = nickname == null || nickname == '' ? 'empty' : nickname;
            description = description == null || description == '' ? 'empty' : description;
            level = level == null ? 'all' : level

            var startDate = $("#startDate").val();
            var endDate = $("#endDate").val();

            startDate = startDate == null || startDate == '' ? 'empty' : startDate;
            endDate = endDate == null || endDate == '' ? 'empty' : endDate;

            console.debug(startDate + '-------' + endDate);
            //console.debug(tagflg+'-------'+replieflg);
            //$("#startDate").focus();
            //$("#endDate").focus();
            //$("#btnSearch").focus();

            $location.path('/recommendQuestion/' + communityId + '/' + category + '/' + tagflg + '/' + replieflg + '/' + nickname + '/' + description + '/' + startDate + '/' + endDate + '/' + level);
        };

        $scope.recommendQuestion = function (questionId, flag) {
            if (flag) {
                flag = false
            } else {
                flag = true
            }
            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/question/recommendQuestion/' + questionId + '/' + flag, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.getRecommendList(commId, cate, istag, isreplie, nick, desc, startdate, enddate, level);
            }).error(function () {
            });
        };

        //跳转到问题修改页面
        $scope.gotoQuestionEditPage = function (objId) {
            var community = commId == null ? 'all' : commId;
            var category = cate == null ? 'all' : cate;
            var tagflg = istag == null ? 'all' : istag;
            var replieflg = isreplie == null ? 'all' : isreplie;
            var nickname = nick == null || nick == '' ? 'empty' : nick;
            var description = desc == null || desc == '' ? 'empty' : desc;
            var start = startdate == null || startdate == '' ? 'empty' : startdate;
            var end = enddate == null || enddate == '' ? 'empty' : enddate;
            var le = level == null ? 'all' : level;

            //console.debug(objId+'----------'+tagflg+'-------'+replieflg);

            $location.path('/questionManager/edit/' + objId + '/' + community + '/' + category + '/' + tagflg + '/' + replieflg + '/' + nickname + '/' + description + '/' + start + '/' + end + '/' + le);
        };

        //添加到新鲜事
        $scope.addToFreshNews = function (question, title) {
            if (title == null) {
                alert('请输入标题');
                return;
            }
            question.desc = title;

            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/question/addQuestionToFreshNews', question, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.getRecommendList(commId, cate, istag, isreplie, nick, desc, startdate, enddate, level);
            }).error(function () {
            });
        };


        //推送
        $scope.pushQuestion = function (question) {
            $scope.pushMessage = null;
            $('#pushModal').modal('toggle');
            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/question/pushQuestionByTag', question, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.pushMessage = {
                    question: question,
                    uList: data.data
                }
            }).error(function () {
            });
        };

        $scope.confirmPush = function () {
            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/question/confirmPushQuestion', $scope.pushMessage, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {

            }).error(function () {
            });
        };


        //置顶
        $scope.moveToTop = function (questionId) {
            var opt = {
                questionId: questionId,
                communityId: commId,
                category: cate
            };
            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/question/moveQuestionToTop', opt, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.getRecommendList(commId, cate, istag, isreplie, nick, desc, startdate, enddate, level);
            }).error(function () {
            });
        };

        $scope.cancelTop = function (questionId) {
            var opt = {
                questionId: questionId,
                category: cate
            };
            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/question/cancelTopQuestion', opt, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.getRecommendList(commId, cate, istag, isreplie, nick, desc, startdate, enddate, level);
            }).error(function () {

            });
        };

        $scope.onSelectPage = function (page) {
            $scope.currentPage = page;
            $scope.getRecommendList(commId, cate, istag, isreplie, nick, desc, startdate, enddate, level);
        };

        $scope.searchUserQuestion = function (userId) {
            if (userId == null) {
                return;
            }

            $('#userQuestion').modal('toggle');

            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/question/searchUserQuestion/' + userId, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.userQuestionList = data.data;
            }).error(function () {
            });
        };

        $scope.sendReply = function (questionId, reply) {

            if (reply == null) {
                alert('回复内容不能为空')
            } else {

                $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/admin/backOfficePostReply/' + questionId, reply, {
                    headers: {'Content-Type': 'application/json;charset=utf-8'}
                }).success(function (data) {
                    var temp = {
                        replyDesc: reply.replies.replyDesc,
                        dateReplied: new Date(),
                        repliedBy: {
                            nickName: '小6客服'
                        }
                    };

                    $scope.recommendList.forEach(function (question) {
                        if (question.objId == questionId) {
                            question.replies.push(temp)
                        }
                    });
                }).error(function () {
                });
            }
        };

        $scope.changeCategory = function (questionId, category) {
            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/question/changeQuestionCategory/' + questionId + '/' + category, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.getRecommendList(commId, cate, istag, isreplie, nick, desc, startdate, enddate, level);
            }).error(function () {
            });
        }

        //删除一个提问
        $scope.deleteQuestion = function (objId) {
            bootbox.confirm('是否删除问题', function (result) {
                if (result == true) {
                    $http.delete('http://' + backOfficeHost + '/rest/v1.0/Questions/deleteQuestion/' + objId + '/1/1', {
                        headers: {'Content-Type': 'application/json;charset=utf-8'}
                    }).success(function (data) {
                        $scope.getRecommendList(commId, cate, istag, isreplie, nick, desc, startdate, enddate, level);
                    }).error(function () {
                    });
                }
            }).find("div.modal-dialog").css({width: '30%'});
        };

        $scope.changeLevel = function (id, le) {
            var input = {
                questionId: id,
                level: le
            };
            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/question/changeQuestionLevel', input, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.getRecommendList(commId, cate, istag, isreplie, nick, desc, startdate, enddate, level);
            }).error(function () {
            });
        }
    }
    ]).directive('paging', function () {
        return {
            restrict: 'E',
            //scope: {
            //    numPages: '=',
            //    currentPage: '=',
            //    onSelectPage: '&'
            //},
            template: '',
            replace: true,
            link: function (scope, element, attrs) {
                scope.$watch('currentPage', function (value) {
                    scope.pages = [];
                    for (var i = value - 5 > 0 ? value - 5 : 1; i <= (value + 5 > scope.totalPage ? scope.totalPage : value + 5); i++) {
                        scope.pages.push(i);
                    }
                });
                scope.$watch('totalPage', function (value) {
                    scope.pages = [];
                    for (var i = scope.currentPage - 5 > 0 ? scope.currentPage - 5 : 1; i <= (scope.currentPage + 5 > value ? value : scope.currentPage + 5); i++) {
                        scope.pages.push(i);
                    }
                });

                scope.isActive = function (page) {
                    return scope.currentPage === page;
                };
                scope.selectPage = function (page) {
                    if (!scope.isActive(page)) {
                        scope.currentPage = page;
                        scope.onSelectPage(page);
                    }
                };
                scope.selectPrevious = function () {
                    if (!scope.noPrevious()) {
                        scope.selectPage(scope.currentPage - 1);
                    }
                };
                scope.selectNext = function () {
                    if (!scope.noNext()) {
                        scope.selectPage(scope.currentPage + 1);
                    }
                };
                scope.noPrevious = function () {
                    return scope.currentPage == 1;
                };
                scope.noNext = function () {
                    return scope.currentPage == scope.totalPage;
                };

            }
        };
    });
